package com.jiuyou.storeController.coupons;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.coupons.domain.Coupons;
import com.ruoyi.coupons.service.ICouponsService;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chengliang
 * @date 2021/11/24
 **/
@RestController
@RequestMapping("/store/coupons")
@Api(tags = {"优惠券列表"})

public class CouponsStoreController extends StoreBaseController {
    private static final Logger log = LoggerFactory.getLogger(CouponsStoreController.class);

    @Autowired
    private ICouponsService couponsService;

    @Autowired
    private IStoreProductService productService;

    @PostMapping("/add")
    @ApiOperation("创建优惠券")
    public Coupons create(@ApiParam @RequestBody Coupons coupons){

        StoreUserRole role = getStoreUserRole();
        coupons.setCreateBy(getLoginStoreUserId());
        coupons.setCreateType(DicConstants.BUSINESS_Business.getCode());
        coupons.setState(DicConstants.SYS_Y.getCode());
        coupons.setStoreId(role.getStoreId());
        if(DicConstants.SYS_N.getCode().equals(coupons.getFixedTimeState())){
            String s = DateUtils.dateTimeHMS(coupons.getUseEndTime());
            String[] s1 = s.split(" ");
            coupons.setUseEndTime(DateUtils.parseDate(s1[0]+" 23:59:59"));
        }
//        //如果是限量券
//        if(DicConstants.SYS_Y.equals(coupons.getLimitedState())){
//            //把总数量赋给剩余数量
//            coupons.setLastTotal(coupons.getTotal());
//        }
        couponsService.insertCoupons(coupons);
        //所关联的商品或分类ID
        //
        if(DicConstants.COUPON_TYPE_Product.getCode().equals(coupons.getCouponType())){
            String[] primaryKey = StringUtils.deleteArrayNull(coupons.getPrimaryKey().split(","));
            List<Long> collect = Arrays.stream(primaryKey)
                    .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            List<StoreProduct> products = productService.selectByClassifyOrId(role.getStoreId(),collect);
            List<StoreProduct> update= new ArrayList<>();
            BigDecimal decimal = BigDecimal.ZERO;
            for (StoreProduct product : products) {
                //如果商品已经有优惠了
                if (null != product.getCouponsMaxAll()) {
                    decimal = product.getCouponsMaxAll();
                }
                //如果商品是没有门槛或者金额门槛小于商品价格
                if(coupons.getMinPrice().compareTo(BigDecimal.ZERO) == 0 || coupons.getMinPrice().compareTo(product.getPrice()) < 0){
                    //看下当前优惠券面值是否高过原有优惠
                    if(coupons.getMinPrice().compareTo(decimal) > 0){
                        product.setCouponsMaxAll(coupons.getMoney());
                        update.add(product);
                        productService.updateStoreProduct(product);
                        continue;
                    }
                }
            }
        }

        return coupons;
    }
    @GetMapping("/list")
    @ApiOperation("获取优惠券列表")
    public TableDataInfo getList(String state){
        StoreUserRole role = getStoreUserRole();
        Coupons coupons = new Coupons();
        coupons.setStoreId(role.getStoreId());
        if(!"all".equals(state)){
            coupons.setState(state);
        }
        startPage();
        List<Coupons> list = couponsService.selectCouponsList(coupons);
        return getDataTable(list);
    }
    @GetMapping("/shelves/{couponId}")
    @ApiOperation("启用优惠券")
    public JSONObject shelves(@PathVariable Long couponId){
        StoreUserRole role = getStoreUserRole();
        JSONObject jsonObject = returnFail();

        Coupons coupons = couponsService.selectCouponsById(couponId);
        coupons.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        coupons.setUpdateBy(getLoginStoreUserId());
        coupons.setState(DicConstants.SYS_Y.getCode());
        couponsService.updateCoupons(coupons);
        jsonObject = returnSuccess(jsonObject);
        return jsonObject;
    }
    @GetMapping("/shelves/up/{couponId}")
    @ApiOperation("启用优惠券")
    public JSONObject shelvesUp(@PathVariable Long couponId){
        StoreUserRole role = getStoreUserRole();
        JSONObject jsonObject = returnFail();

        Coupons coupons = couponsService.selectCouponsById(couponId);
        coupons.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        coupons.setUpdateBy(getLoginStoreUserId());
        coupons.setState(DicConstants.SYS_Y.getCode());
        couponsService.updateCoupons(coupons);
        jsonObject = returnSuccess(jsonObject);
        return jsonObject;
    }
    @GetMapping("/shelves/down/{couponId}")
    @ApiOperation("停用优惠券")
    public JSONObject shelvesDown(@PathVariable Long couponId){
        StoreUserRole role = getStoreUserRole();
        JSONObject jsonObject = returnFail();

        Coupons coupons = couponsService.selectCouponsById(couponId);
        coupons.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        coupons.setUpdateBy(getLoginStoreUserId());
        coupons.setState(DicConstants.SYS_N.getCode());
        couponsService.updateCoupons(coupons);
        jsonObject = returnSuccess(jsonObject);
        return jsonObject;
    }
    @DeleteMapping("/{couponId}")
    @ApiOperation("删除优惠券")
    public JSONObject delete(@PathVariable Long couponId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success",false);
        jsonObject.put("msg","删除失败");

        StoreUserRole role = getStoreUserRole();
        Coupons coupons = couponsService.selectCouponsById(couponId);
        if(role == null || coupons.getStoreId() != role.getStoreId()){
            jsonObject.put("msg","权限不足");
            return jsonObject;
        }
        coupons.setState(DicConstants.SYS_N.getCode());
        coupons.setUpdateBy(getLoginStoreUserId());
        coupons.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        coupons.setDelState(DicConstants.SYS_Y.getCode());
        coupons.setDelTime(new Date());
        coupons.setDelType(DicConstants.BUSINESS_Business.getCode());
        coupons.setDelUser(getLoginStoreUserId());
        couponsService.updateCoupons(coupons);
        return jsonObject;
    }

    /**
     * 要包含
     * @param couponId
     * @return
     */
    @GetMapping("/{couponId}")
    @ApiOperation("优惠券详情")
    public JSONObject detail(@PathVariable Long couponId){
        JSONObject jsonObject = returnFail();

        StoreUserRole role = getStoreUserRole();
        Coupons coupons = couponsService.selectCouponsById(couponId);
        if(role == null || coupons.getStoreId() != role.getStoreId()){
            jsonObject.put("msg","权限不足");
            return jsonObject;
        }
        jsonObject.put("coupons",coupons);
        returnSuccess(jsonObject);
        return jsonObject;
    }

}
